package cn.itcast.bos.web.action.base;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.BaseAction;
import cn.itcast.bos.utils.PinYin4jUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import sun.management.resources.agent;
import sun.misc.BASE64Encoder;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.ServletOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2017/7/21.
 */
@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("protoType")
public class AreaAction extends BaseAction<Area> {

    //接收上传的文件
    private File file;

    public void setFile(File file) {
        this.file = file;
    }

    //注入Service
    @Autowired
    private AreaService areaService;

    //文件导入的方法
    @Action(value="area_import")
    public void  areaImport(){
        //定义一个数组,用于存储area对象
        List<Area> areas = new ArrayList<>();
        //解析Excel文件,解析xls文件使用hssf,解析xlsx文件使用xssf
       try {
           HSSFWorkbook hssf = new HSSFWorkbook(new FileInputStream(file));

           //读取一个sheet中的数据
           HSSFSheet sheet = hssf.getSheetAt(0);
           //读取sheet中的每一行
           for(Row row:sheet){
               //一行数据,对应一个area对象
               //第一行时表头,跳过
               if(row.getRowNum()==0){
                   continue;
               }
               //跳过空行
               if(row.getCell(0)==null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
                    continue;
               }

               model.setId(row.getCell(0).getStringCellValue());
               model.setProvince(row.getCell(1).getStringCellValue());
               model.setCity(row.getCell(2).getStringCellValue());
               model.setDistrict(row.getCell(3).getStringCellValue());
               model.setPostcode(row.getCell(4).getStringCellValue());
               //基于pinyin4J成成城市编码和简码
               String province = model.getProvince().substring(0,model.getProvince().length()-1);
               String  city = model.getCity().substring(0,model.getCity().length()-1);
               String district = model.getDistrict().substring(0,model.getDistrict().length()-1);
               String [] handarray = PinYin4jUtils.getHeadByString(province+city+district);
               StringBuffer buffer = new StringBuffer();
               for(String hand:handarray){
                   buffer.append(hand);
               }
               model.setShortcode(buffer.toString());
               //生成城市编码
               String cityCode = PinYin4jUtils.hanziToPinyin(city,"");
               model.setCitycode(cityCode);
               //将area添加到集合中
               areas.add(model);
           }

           //调用业务层
           areaService.save(areas);
       }catch (Exception e){
           e.printStackTrace();
       }
    }
    //分页查询区域的方法
    private int page;
    private int rows;

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    @Action(value="area_pageQuery",results = {@Result(name="success",type = "json")})
    public String pageQuery() {
        //构建分页查询对象
        Pageable pageable = new PageRequest(page-1,rows);
        //构建条件查询对象
        Specification<Area> specification = new Specification<Area>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                //构建一个list 用来存储查询条件
                List<Predicate> list = new ArrayList<>();
                if(StringUtils.isNotBlank(model.getProvince())){
                    Predicate p1 = cb.like(root.get("province").as(String.class),"%"+model.getProvince()+"%");
                    list.add(p1);
                }
                if(StringUtils.isNotBlank(model.getCity())){
                    Predicate p2 = cb.like(root.get("city").as(String .class),"%"+model.getCity()+"%");
                    list.add(p2);
                }
                if(StringUtils.isNotBlank(model.getDistrict())){
                    Predicate p3 = cb.like(root.get("district").as(String.class),"%"+model.getDistrict()+"%");
                    list.add(p3);
                }
                Predicate p4 = cb.isNull(root.get("status").as(Character.class));
                list.add(p4);

                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        //调用业务层查询
        Page<Area> pageData =  areaService.pageQuery(specification,pageable);
        pushPageDataToValueStack(pageData);
        return SUCCESS;
    }
    //保存或者修改的action
    @Action(value="area_save",results = {@Result(name="success",type="redirect",location = "./pages/base/area.html")})
    public String saveArea(){
        areaService.save(model);
        return SUCCESS;
    }
    //删除的方法
    private String ids;

    public void setIds(String ids) {this.ids = ids;}
    @Action(value = "area_del",results = {@Result(name="success",type="redirect",location = "./pages/base/area.html")})
    public String delTag(){
        //将ids 按照","截取
        String[] idArray = ids.split(",");
        areaService.del(idArray);
        return SUCCESS;
    }
    //文件下载的方法
    @Action(value="area_export")
    public String downLoad(){
        //1.拿到要导出的数据
        List<Area> areaList = areaService.findAll();
        //2,创建一个工作簿
        HSSFWorkbook workbook= new HSSFWorkbook();
        //3.创建一个sheet
        HSSFSheet sheet = workbook.createSheet();
        //4.填充数据
        //4.1设置第一行
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("省");
        row.createCell(2).setCellValue("市");
        row.createCell(3).setCellValue("区/县");
        row.createCell(4).setCellValue("邮编");
        row.createCell(5).setCellValue("城市编码");
        row.createCell(6).setCellValue("简码");
        //4.2 填充数据
        if(areaList !=null &&areaList.size() !=0){
            for(int i=1;i<=areaList.size();i++){
                    model =areaList.get(i-1);
                HSSFRow temp = sheet.createRow(i);
                temp.createCell(0).setCellValue(model.getId());
                temp.createCell(1).setCellValue(model.getProvince());
                temp.createCell(2).setCellValue(model.getCity());
                temp.createCell(3).setCellValue(model.getDistrict());
                temp.createCell(4).setCellValue(model.getPostcode());
                temp.createCell(5).setCellValue(model.getCitycode());
                temp.createCell(6).setCellValue(model.getShortcode());
            }
        }

        //5.设置两个头,一个流,写回页面下载
        try {
            ServletOutputStream os =ServletActionContext.getResponse().getOutputStream();
            String filename = "区域信息.xls";
            //filename =new String(filename.getBytes(),"ISO-8859-1");
            //根据浏览器处理中文乱码问题
           // String agent = ServletActionContext.getRequest().getHeader("User-Agent");
            /*if(agent.contains("Firefox")){
                filename = base64EncodeFileName(filename);
            }else{
                filename = URLEncoder.encode(filename,"UTF-8");
            }*/
            //设置头
            ServletActionContext.getResponse().setContentType(ServletActionContext.getServletContext().getMimeType(filename));
            ServletActionContext.getResponse().setHeader("content-disposition","attachement;filename:"+filename);
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return NONE;
    }
    //处理中文乱码问题的方法
    public static String base64EncodeFileName(String fileName) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            return "=?UTF-8?B?"
                    + new String(base64Encoder.encode(fileName
                    .getBytes("UTF-8"))) + "?=";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}


